#include <Arduino.h>
#include "Audio.h"
#include "SPI.h"
#include "SD.h"
#include "FS.h"

extern Audio audio;

bool play_flag = true;
bool isFirst = true;
File lastFile;
File currentFile;
File root;

void getNextFile() {
  String fileName;
  if (isFirst) {
    isFirst = false;
    root = SD.open("/");
    if (!root) {
      Serial.println("Failed to open directory");
      return;
    }
  }

  lastFile = currentFile;
  currentFile = root.openNextFile();
  if (currentFile) {
    if (currentFile.isDirectory()) {
      getNextFile();
    } else {
      fileName = currentFile.name();
      fileName.toLowerCase();
      if (fileName.indexOf(".mp3") < 0) {
        getNextFile();
      }
    }
  } else {
    isFirst = true;
    getNextFile();
  }
}

void playLastAudio() {
  String sdfile;
  if (lastFile) {
    sdfile = lastFile.name();
    Serial.println("开始播放" + sdfile);
    audio.connecttoFS(SD, sdfile.c_str());
  }
  currentFile = lastFile;
}

void stopAudio() {
  audio.pauseResume();
  play_flag != play_flag;
  Serial.println(play_flag);
}

void playNextAudio() {
  String sdfile;
  getNextFile();
  if (currentFile) {
    sdfile = currentFile.name();
    Serial.println("开始播放" + sdfile);
    audio.connecttoFS(SD, sdfile.c_str());
  }
}

void Play_Other_Laba() {
  audio.connecttoFS(SD, "/4G/laba.mp3");
}

void Play_Other_Niganma() {
  audio.connecttoFS(SD, "/4G/niganma.mp3");
}

void Play_Other_Rangyixia() {
  audio.connecttoFS(SD, "/4G/rangyixia.mp3");
}

void Play_Other_Goujiao() {
  audio.connecttoFS(SD, "/4G/goujiao.mp3");
}